public class Solution79 {
    public boolean exist(char[][] board, String word) {
        boolean[][] visited = new boolean[board.length][board[0].length];
        boolean res;
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == word.charAt(0)) {
                    visited[i][j] = true;
                    res = dfs(board, i, j, 1, visited, word);
                    if (res) {
                        return true;
                    }
                    visited[i][j] = false;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, int i, int j, int k, boolean[][] visited, String word) {
        if (k == word.length()) {
            return true;
        }
        boolean res;
        if (i < board.length - 1 && !visited[i + 1][j] && board[i + 1][j] == word.charAt(k)) {
            visited[i + 1][j] = true;
            res = dfs(board, i + 1, j, k + 1, visited, word);
            if (res) {
                return true;
            }
            visited[i + 1][j] = false;
        }
        if (i > 0 && !visited[i - 1][j] && board[i - 1][j] == word.charAt(k)) {
            visited[i - 1][j] = true;
            res = dfs(board, i - 1, j, k + 1, visited, word);
            if (res) {
                return true;
            }
            visited[i - 1][j] = false;
        }
        if (j < board[0].length - 1 && !visited[i][j + 1] && board[i][j + 1] == word.charAt(k)) {
            visited[i][j + 1] = true;
            res = dfs(board, i, j + 1, k + 1, visited, word);
            if (res) {
                return true;
            }
            visited[i][j + 1] = false;
        }
        if (j > 0 && !visited[i][j - 1] && board[i][j - 1] == word.charAt(k)) {
            visited[i][j - 1] = true;
            res = dfs(board, i, j - 1, k + 1, visited, word);
            if (res) {
                return true;
            }
            visited[i][j - 1] = false;
        }
        return false;
    }
}
